package com.spzx.service.impl;


import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.domain.*;
import com.spzx.mapper.BrandMapper;
import com.spzx.mapper.ProductMapper;
import com.spzx.product.api.domain.Product;
import com.spzx.product.api.domain.ProductSku;
import com.spzx.product.api.domain.SkuPrice;
import com.spzx.product.api.domain.VO.ItemVO;
import com.spzx.product.api.domain.VO.SkuStockVO;
import com.spzx.service.*;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;


@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {
    @Resource
    CategoryService categoryService;
    @Resource
    ProductMapper productMapper;
    @Resource
    BrandMapper brandMapper;
    @Resource
    ProductDetailsService productDetailsService;
    @Resource
    ProductSpecService productSpecService;
    @Resource
    ProductSkuService productSkuService;
    @Resource
    SkuStockService skuStockService;
    @Resource
    BrandService brandService;

    @Override
    public List<Product> listByCondition(Product product) {
       /* String name = product.getName();
        Long brandId = product.getBrandId();
        Long category3Id = product.getCategory3Id();
        Long category2Id = product.getCategory2Id();
        Long category1Id = product.getCategory1Id();

        List<Product> list = this.list(Wrappers.lambdaQuery(Product.class)
                .eq(brandId != null, Product::getBrandId, brandId)
                .eq(category1Id != null, Product::getCategory1Id, category1Id)
                .eq(category2Id != null, Product::getCategory2Id, category2Id)
                .eq(category3Id != null, Product::getCategory3Id, category3Id)
                .like(name != null, Product::getName, name)).stream().map(product1 -> {
                    product1
        }).toList();*/
        List<Product> products = productMapper.listByCondition(product);
        return products;
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertProduct(Product product) {
        try {
            Long brandId = product.getBrandId();
            Long category3Id = product.getCategory3Id();
            Long category2Id = product.getCategory2Id();
            Long category1Id = product.getCategory1Id();
            product.setBrandName(brandService.getById(brandId).getName());
            product.setCategory1Name(categoryService.getById(category1Id).getName());
            product.setCategory2Name(categoryService.getById(category2Id).getName());
            product.setCategory3Name(categoryService.getById(category3Id).getName());
            this.save(product);
            //AtomicInteger i = new AtomicInteger(0);

            List<ProductSku> productSkuList = product.getProductSkuList();
          /* product.getProductSkuList().stream().map(productSku->{
               productSku.setSkuCode(product.getId()+"_"+i);
               productSku.setProductId(product.getId());
               productSkuService.save(productSku);
               Integer stockNum = productSku.getStockNum();
               skuStock.setAvailableNum(stockNum);
               skuStock.setLockNum(0);
               skuStock.setTotalNum(stockNum);
               skuStock.setSaleNum(0);
               skuStockService.save(skuStock);
               return productSku;
           });*/
            for (int j = 0; j < productSkuList.size(); j++) {
                SkuStock skuStock = new SkuStock();
                ProductSku productSku = new ProductSku();
                BeanUtils.copyProperties(productSkuList.get(j), productSku);
                productSku.setSkuCode(product.getId() + "_" + j);
                productSku.setProductId(product.getId());
                productSkuService.save(productSku);
                Integer stockNum = productSku.getTotalNum();
                skuStock.setSkuId(productSku.getId());
                skuStock.setAvailableNum(stockNum);
                skuStock.setLockNum(0);
                skuStock.setTotalNum(stockNum);
                skuStock.setSaleNum(0);
                skuStock.setStatus(null);
                skuStockService.save(skuStock);

            }
            List<String> productDetailsIdList = product.getProductDetailsIdList();
            ProductDetails productDetails = new ProductDetails();
            /*for (int j = 0; j < productDetailsIdList.size(); j++) {
                productDetails.setImageUrls(productDetailsIdList.get(j));
                productDetails.setProductId(product.getId());
                productDetailsService.save(productDetails);
            }*/
            productDetails.setImageUrls(String.join(",", product.getProductDetailsIdList()));
            productDetails.setProductId(product.getId());
            productDetailsService.save(productDetails);
        } catch (Exception e) {
            throw new ServiceException("新增失败");
        }
        return true;
    }

    @Override
    public Product getDetails(Long id) {
        Product byId = this.getById(id);
        List<ProductSku> productSkuList = productSkuService.list(Wrappers.lambdaQuery(ProductSku.class).eq(ProductSku::getProductId, id));
        List<String> productDetailsList = productDetailsService.list(Wrappers.lambdaQuery(ProductDetails.class).eq(ProductDetails::getProductId, id)).stream().map(productDetails -> {
            return productDetails.getImageUrls();
        }).toList();
        productSkuList.stream().map(productSku -> {
            productSku.setTotalNum(skuStockService.getOne(Wrappers.lambdaQuery(SkuStock.class).eq(SkuStock::getSkuId, productSku.getId())).getTotalNum());
            return productSku;
        }).collect(Collectors.toList());
        byId.setProductDetailsIdList(productDetailsList);
        byId.setProductSkuList(productSkuList);
        return byId;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateDetails(Product product) {
        try {
            List<String> productDetailsIdList = product.getProductDetailsIdList();
            List<ProductSku> productSkuList = product.getProductSkuList();
            productSkuList.forEach(productSku -> {
                productSkuService.updateById(productSku);
                Integer stockNum = productSku.getTotalNum();
                SkuStock skuStock = skuStockService.getOne(Wrappers.lambdaQuery(SkuStock.class).eq(SkuStock::getSkuId, productSku.getId()));
                skuStock.setTotalNum(stockNum);
                skuStock.setAvailableNum(stockNum - skuStock.getLockNum());
                skuStockService.updateById(skuStock);
            });
            ProductDetails productDetails = productDetailsService.getOne(Wrappers.lambdaQuery(ProductDetails.class).eq(ProductDetails::getProductId, product.getId()));
            productDetails.setImageUrls(String.join(",", productDetailsIdList));
            productDetailsService.updateById(productDetails);
            this.updateById(product);
        } catch (Exception e) {
            throw new ServiceException("更新失败");
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteByIds(Long[] ids) {
        try {
            for (int i = 0; i < ids.length; i++) {
                productDetailsService.remove(Wrappers.lambdaQuery(ProductDetails.class).eq(ProductDetails::getProductId, ids[i]));
                List<Boolean> collect = productSkuService.list(Wrappers.lambdaQuery(ProductSku.class).eq(ProductSku::getProductId, ids[i]))
                        .stream().map(productSku -> {
                            System.out.println("?????????");
                            boolean remove = skuStockService.remove(Wrappers.lambdaQuery(SkuStock.class).eq(SkuStock::getSkuId, productSku.getId()));
                            return remove;
                        }).collect(Collectors.toList());
                productSkuService.remove(Wrappers.lambdaQuery(ProductSku.class).eq(ProductSku::getProductId, ids[i]));
                this.remove(Wrappers.lambdaQuery(Product.class).eq(Product::getId, ids[i]));
            }
        } catch (Exception e) {
            throw new ServiceException("删除失败");
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateStatus(Long id, Short status) {
        Product byId = this.getById(id);
        byId.setStatus(status);
        return this.updateById(byId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateAuditStatus(Long id, Short auditStatus) {
        try {
            Product byId = this.getById(id);
            byId.setAuditStatus(auditStatus);
            if (auditStatus == 0) {
                byId.setAuditMessage("未审核");

            } else if (auditStatus == 1) {
                byId.setAuditMessage("审核通过");
            } else if (auditStatus == -1) {
                byId.setAuditMessage("审核未通过");
            }
            return this.updateById(byId);
        } catch (Exception e) {
            throw new ServiceException("删除失败");
        }

    }

    @Override
    public ItemVO itemById(Long id) {
        ItemVO itemVO = new ItemVO();
        ProductSku productSku = productSkuService.getById(id);
        Product product = this.getById(productSku.getProductId());
        List<String> detailsImageUrls =new ArrayList<>();
        productDetailsService
                .list(Wrappers.lambdaQuery(ProductDetails.class).eq(ProductDetails::getProductId,product.getId()))
                .stream().map(productDetails -> {
                    detailsImageUrls.add(productDetails.getImageUrls()) ;
                    return productDetails;}).collect(Collectors.toList());
        List<String> sliderUrlList = Arrays.asList(product.getSliderUrls().split(","));
        JSONArray specValue = JSONArray.parseArray(product.getSpecValue());
        SkuPrice skuPrice = new SkuPrice(id, productSku.getSalePrice(), productSku.getMarketPrice());
        List<ProductSku> productSkuList = productSkuService.list(Wrappers.lambdaQuery(ProductSku.class).eq(ProductSku::getProductId,product.getId()));
        Map<String,Long> skuSpecMap = new HashMap<>();
        productSkuList.stream().map(productSku1 -> {
            skuSpecMap.put(productSku1.getSkuSpec(),productSku1.getId());
            return productSku1;
        }).collect(Collectors.toList());
        SkuStock skuStock = skuStockService.getById(id);
        SkuStockVO skuStockVO = new SkuStockVO(id,skuStock.getAvailableNum(),skuStock.getSaleNum());
        itemVO.setSkuPrice(skuPrice);
        itemVO.setSpecValueList(specValue);
        itemVO.setSliderUrlList(sliderUrlList);
        itemVO.setProduct(product);
        itemVO.setDetailsImageUrlList(detailsImageUrls);
        itemVO.setProductSku(productSku);
        itemVO.setSkuStockVo(skuStockVO);
        itemVO.setSkuSpecValueMap(skuSpecMap);
        return itemVO;
    }

}
